package com.xihu.credit.controller;

import com.xihu.credit.service.MailService;
import com.xihu.credit.service.UserService;
import com.xihu.credit.entity.User;
import com.xihu.credit.util.VerificationCodeCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private MailService mailService;


    /**
     * 用户注册接口
     * @param user 用户对象
     * @return 注册结果
     */
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();

        if (!user.getEmail().matches("^[\\w.-]+@[\\w.-]+\\.\\w+$")) {
            result.put("code", 400);
            result.put("message", "邮箱格式不正确");
            return result;
        }

        String status = userService.register(user);
        switch (status) {
            case "email_exists":
                result.put("code", 409);
                result.put("message", "邮箱已被注册");
                break;
            case "mobile_exists":
                result.put("code", 409);
                result.put("message", "手机号已注册");
                break;
            case "success":
                result.put("code", 200);
                result.put("message", "注册成功");
                break;
            default:
                result.put("code", 500);
                result.put("message", "注册失败，请稍后再试");
        }

        return result;
    }

    /**
     * 用户登录接口
     * @param user 用户名
     * @return 登录结果
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        User existingUser = userService.login(user.getUsername(), user.getPassword());

        if (existingUser != null) {
            result.put("code", 200);
            result.put("message", "登录成功");
            result.put("profile", existingUser.getProfile());   // ✅ 返回头像路径
            result.put("username", existingUser.getUsername()); // ✅ 可选，返回用户名
            result.put("id",existingUser.getId());
            result.put("token", UUID.randomUUID().toString()); // 生成假的 token，你可以改为 JWT 等
        } else {
            result.put("code", 401);
            result.put("message", "用户名或密码错误");
        }

        return result;
    }

    /**
     * 获取用户信息接口
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public User getUserInfo(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    /**
     * 更新用户信息接口
     * @param user 更新后的用户信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public String updateUser(@RequestBody User user) {
        int result = userService.updateUser(user);
        if (result > 0) {
            return "更新成功";
        }
        return "更新失败";
    }
    @PostMapping("/send-code")
    public Map<String, Object> sendCode(@RequestBody Map<String, String> body) {
        String email = body.get("email");
        Map<String, Object> result = new HashMap<>();

        if (email == null || !email.matches("^[\\w.-]+@[\\w.-]+\\.\\w+$")) {
            result.put("code", 400);
            result.put("message", "邮箱格式不正确");
            return result;
        }

        // 生成6位验证码
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        // 缓存到内存（生产建议使用 Redis）
        VerificationCodeCache.store(email, code);

        // 发送邮件
        try {
            mailService.sendSimpleMail(email, "找回密码验证码", "您的验证码是：" + code + "，10分钟内有效。");
            result.put("code", 200);
            result.put("message", "验证码发送成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "发送失败");
        }

        return result;
    }

    @PostMapping("/reset-password-by-code")
    public Map<String, Object> resetPasswordByCode(@RequestBody Map<String, String> body) {
        String email = body.get("email");
        String code = body.get("code");
        String newPassword = body.get("password");

        Map<String, Object> result = new HashMap<>();

        // 验证码校验
        if (!VerificationCodeCache.verify(email, code)) {
            result.put("code", 403);
            result.put("message", "验证码错误或已过期");
            return result;
        }

        User user = userService.findByEmail(email);
        if (user == null) {
            result.put("code", 404);
            result.put("message", "该邮箱未注册");
            return result;
        }

        user.setPassword(newPassword);
        userService.updatePasswordByEmail(email,newPassword);
        result.put("code", 200);
        result.put("message", "密码已重置");
        return result;
    }
    @GetMapping("/info")
    public Map<String, Object> getUserInfoByUsername(@RequestParam String username) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.findByUsername(username);
        if (user != null) {
            result.put("code", 200);
            result.put("user", user);
        } else {
            result.put("code", 404);
            result.put("message", "用户不存在");
        }

        return result;
    }
    @PutMapping("/change-password")
    public Map<String, Object> changePassword(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String newPassword = body.get("password");
        System.out.println(newPassword);

        Map<String, Object> result = new HashMap<>();

        if (username == null || newPassword == null || newPassword.trim().isEmpty()) {
            result.put("code", 400);
            result.put("message", "参数不完整");
            return result;
        }

        int updateResult = userService.updatePasswordByUsername(username, newPassword);
        if (updateResult > 0) {
            result.put("code", 200);
            result.put("message", "密码修改成功");
        } else {
            result.put("code", 404);
            result.put("message", "用户不存在或修改失败");
        }

        return result;
    }
    @PostMapping("/upload-avatar")
    public Map<String, Object> uploadAvatar(@RequestParam("file") MultipartFile file,
                                            @RequestParam("username") String username) {
        Map<String, Object> result = new HashMap<>();

        if (file.isEmpty()) {
            result.put("code", 400);
            result.put("message", "文件为空");
            return result;
        }

        try {
            // ❗设置前端 public/magic 路径（注意是绝对路径，按你的实际路径改）
            String frontendPath = "C:/Users/86130/xihuhh/xihufen--template/public/magic/";
            File dir = new File(frontendPath);
            if (!dir.exists()) dir.mkdirs();

            // 重命名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + suffix;

            // 保存
            File dest = new File(frontendPath + newFileName);
            file.transferTo(dest);

            // 构建图片访问路径
            String avatarUrl = "/magic/" + newFileName;

            // 更新数据库头像地址
            userService.updateProfile(username, avatarUrl);

            result.put("code", 200);
            result.put("url", avatarUrl); // 给前端用来展示头像
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "头像上传失败");
            e.printStackTrace();
        }

        return result;
    }



}

